package com.ds.infrastructure.audit.client.track;

import com.alibaba.fastjson.JSON;
import com.ds.infrastructure.audit.common.entity.KbaBehaviorWrapper;
import com.ds.infrastructure.audit.common.exception.KbaAuditException;
import com.ning.http.client.*;
import lombok.extern.slf4j.Slf4j;

/**
 * 作用：
 *
 * @author WeiShaoying
 * @date 2020/7/27
 */
@Slf4j
public class KbaProtocolTrackAsyncHttp extends AbstractKbaTrack {


    private AsyncHttpClient asyncHttpClient;

    public KbaProtocolTrackAsyncHttp(String server) {
        super(server);
    }

    public KbaProtocolTrackAsyncHttp(String server, String appName, String appKey) {
        super(server, appName, appKey);
    }

    /**
     * 初始化
     */
    @Override
    public void initialize() {
        AsyncHttpClientConfig config = new AsyncHttpClientConfig.Builder()
                .setConnectTimeout(30 * 1000)
                .setReadTimeout(30 * 1000)
                .build();
        asyncHttpClient = new AsyncHttpClient(config);
    }

    /**
     * Kba上报
     *
     * @param wrapper
     * @throws KbaAuditException
     */
    @Override
    public void report0(KbaBehaviorWrapper wrapper) throws KbaAuditException {
        ListenableFuture<Response> future = asyncHttpClient.preparePost(server)
                .setBody(JSON.toJSONString(wrapper))
                .execute();
//        try {
//            future.get(30, TimeUnit.SECONDS);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    /**
     * 上报并指定回调处理
     *
     * @param wrapper
     * @param callback
     * @throws KbaAuditException
     */
    @Override
    public void report0(KbaBehaviorWrapper wrapper, KbaCallback callback) throws KbaAuditException {
        try {
            callback.preProcess();
            ListenableFuture<Response> future = asyncHttpClient.preparePost(server)
                    .setBody(JSON.toJSONString(wrapper))
                    .execute(
                            new AsyncCompletionHandler<Response>() {
                                @Override
                                public Response onCompleted(Response response) throws Exception {
                                    callback.onSuccess(response);
                                    return response;
                                }

                                @Override
                                public void onThrowable(Throwable t) {
                                    callback.onError(t);
                                    log.error("AsyncHttpClient error:" + t.getMessage(), t);
                                }
                            }
                    );
            callback.onSuccess(future);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            callback.onError(e);
            throw new KbaAuditException(e.getMessage(), e);
        }
    }

}
